package edu.pku.sei.modeler.uml.commands.statemachine;

import org.eclipse.draw2d.geometry.Rectangle;

import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.model.uml.BehaviorStateMachines.Pseudostate;
import edu.pku.sei.modeler.model.uml.BehaviorStateMachines.State;
import edu.pku.sei.modeler.model.uml.BehaviorStateMachines.StateMachine;
import edu.pku.sei.modeler.uml.commands.NestedElementCreateCommand;

public class AdsorbPseudostateCreateCommand extends NestedElementCreateCommand {

	public AdsorbPseudostateCreateCommand(MetaNode node, MetaNode hostNode,
			Rectangle constraint) {
		super(node, hostNode, constraint);
		node.getModelElement().setContainer(fatherNode.getModelElement());
	}
	@Override
	public boolean canExecute() {
		if (node.getModelElement() instanceof Pseudostate)
			return super.canExecute();
		else return false;
	}
	@Override
	protected void updateGraphNode() {
//		node.setAdsorbToContainterNode(true);
		node.setAbsorbToNode(fatherNode);
		if (fatherNode.getParent() == null) {
			fatherNode.getDiagram().getNodes().add(this.node);
		} else {
			this.node.setParent(fatherNode.getParent());
			fatherNode.getParent().getSubNodes().add(this.node);

		}
	}

	@Override
	protected void undoGraphNode() {
		if (fatherNode.getParent() == null) {
			fatherNode.getDiagram().getNodes().remove(this.node);
		} else {
			fatherNode.getParent().getSubNodes().remove(this.node);
			this.node.setParent(null);
		}
	}

	@Override
	protected void updateModelElement() {
		Pseudostate p = (Pseudostate) this.node.getModelElement();
		if (fatherNode.getModelElement() instanceof State) {
			State state = (State) fatherNode.getModelElement();
			if (p.getKind().getValue() == 7) {
				state.getEntry().add(p);
				p.setContainer(state);
			} else if (p.getKind().getValue() == 8) {
				state.getExit().add(p);
				p.setContainer(state);
			}
		} else if (fatherNode.getModelElement() instanceof StateMachine) {
			StateMachine stateMachine = (StateMachine)fatherNode.getModelElement();
			stateMachine.getConnectionPoint().add(p);
		}
	}

	@Override
	protected void undoModelElement() {
		Pseudostate p = (Pseudostate) node.getModelElement();
		if (fatherNode.getModelElement() instanceof State) {
			State state = (State) fatherNode.getModelElement();
			if (p.getKind().getValue() == 7) {
				state.getEntry().remove(p);
				p.setContainer(null);
			} else if (p.getKind().getValue() == 8) {
				state.getExit().remove(p);
				p.setContainer(null);
			}
		} else if (fatherNode.getModelElement() instanceof StateMachine) {
			StateMachine stateMachine = (StateMachine) fatherNode.getModelElement();
			stateMachine.getConnectionPoint().add(p);
		}
	}

	protected void updateNodeBounds() {
		node.setLocationX(constraint.x);
		node.setLocationY(constraint.y);
		node.setWidth(20);
		node.setHeight(20);
	}

}
